<template>
  <div class="component-container">
    <h2>父子组件通信示例</h2>
    
    <div class="section">
      <h3>Props传递和事件触发</h3>
      <p>父组件中的消息: {{ parentMessage }}</p>
      <p>从子组件接收到的消息: {{ childMessage }}</p>
      
      <ChildComponent 
        :message="parentMessage" 
        :user="user"
        @update-message="handleUpdateMessage"
        @send-data="handleChildData"
      />
      
      <!-- 将发送消息和数据的控件移到子组件外面 -->
      <div class="message-controls">
        <div>
          <input 
            v-model="newMessage" 
            placeholder="输入新消息发送给父组件"
          />
          <button @click="sendMessage">发送消息</button>
        </div>
        
        <div>
          <input 
            v-model="dataToSend" 
            placeholder="输入数据发送给父组件"
          />
          <button @click="sendData">发送数据</button>
        </div>
      </div>
    </div>
    
    <div class="section">
      <h3>v-model 双向绑定</h3>
      <p>父组件中的计数: {{ count }}</p>
      <button @click="count++">父组件增加计数</button>
      
      <CounterComponent v-model="count" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import ChildComponent from './ChildComponent.vue'
import CounterComponent from './CounterComponent.vue'

const parentMessage = ref('这是来自父组件的消息')
const childMessage = ref('')
const count = ref(0)

// 添加发送消息和数据的响应式变量
const newMessage = ref('')
const dataToSend = ref('')

const user = reactive({
  name: '张三',
  age: 25,
  email: 'zhangsan@example.com'
})

const handleUpdateMessage = (newMsg) => {
  parentMessage.value = newMsg
}

const handleChildData = (data) => {
  childMessage.value = data
}

// 添加发送消息和数据的方法
const sendMessage = () => {
  handleUpdateMessage(newMessage.value)
  newMessage.value = ''
}

const sendData = () => {
  handleChildData(dataToSend.value)
  dataToSend.value = ''
}
</script>

<style scoped>
.section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.message-controls {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.message-controls div {
  margin: 10px 0;
}

.message-controls input {
  padding: 8px;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
}

.message-controls button {
  padding: 8px 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.message-controls button:hover {
  background-color: #369870;
}
</style>